<?php
namespace app\wechat\controller;

use app\common\controller\StoreBase;
use app\store\model\Store as ShopModel;
use think\facade\Db;
use app\wechat\model\WechatMenu;

class Menu extends StoreBase
{
    protected $noAuth = ['get_menu','send_menu'];
    public function initialize()
    {
        parent::initialize();
        $param = $this->request->param();
        $this->app = wxapi(StoreId(),'weixin');
    }

    /**
     * 自定义菜单
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $list = WechatMenu::field(['id','pid','name','type','key','url','media_id','appid','pagepath','sort_order'])->order('sort_order asc,id asc')->select();
        $list = collection($list)->toArray();
        $a['button'] = wechat_to_tree($list);
        return $this->fetch('index',[
            'list'  => list_to_level($list),
            'menu'  =>  $a,
        ]);
    }

    /**
     * 获取菜单
     * @throws \think\db\exception\DbException
     */
    public function get_menu()
    {
        $app = $this->app;
        $current = $app->menu->current();
        //dump($current);
        $menu = $current['selfmenu_info']['button'];
        //删除所有旧的菜单
        Db::name('wechat_menu')->where('store_id', StoreId())->delete(true);
        //输出一级菜单
        foreach($menu as $r){
            $r['store_id'] = StoreId();
            //是否有子菜单
            if(isset($r['sub_button'])){
                $sub_button = $r['sub_button']['list'];
                $r['sub_button'] = '1';
                $result = WechatMenu::create($r);
                //添加子菜单
                foreach($sub_button as $v){
                    $v['store_id'] = StoreId();
                    $v['pid'] = $result->id;
                    WechatMenu::create_menu($v);
                }
            }else{
                $result = WechatMenu::create_menu($r);
            }
            
        }
        $this->success('获取成功');
    }

    /**
     * 发布菜单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function send_menu()
    {
        $list = WechatMenu::field(['id','pid','name','type','key','url','media_id','appid','pagepath','sort_order'])->order('sort_order asc,id asc')->select();
        $list = collection($list)->toArray();
        //发布
        $app = $this->app;
        $result = $app->menu->create(wechat_to_tree($list));
        if($result['errmsg']=='ok'){
            $this->success('发布成功');
        }else{
            $this->success('发布失败,失败代码:'.$result['errcode']);
        }
        
    }

    /**
     * 添加菜单
     * @param $pid
     * @return mixed
     */
    public function add($pid)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['store_id'] = StoreId();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'wechat_menu');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = WechatMenu::create($param);
            WechatMenu::update_menu($pid);
            $this->success('操作成功');
        }
        $data = WechatMenu::where('pid',$pid)->count();
        if($data >= '3' and $pid =='0'){
            $this->error('一级菜单最多只能3个');
        }elseif($data >= '5' and $pid > '0'){
            $this->error('二级菜单最多只能5个');
        }
        return $this->fetch('save');
    }

    /**
     * 编辑菜单
     * @param $id
     * @param $pid
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id,$pid)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['store_id'] = StoreId();
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'wechat_menu');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            WechatMenu::update($param,['id'=>$param['id']]);
            WechatMenu::update_menu($pid);
            $this->success('操作成功');
        }
        return $this->fetch('save',['data' => WechatMenu::where('id',$id)->find()]);
    }

    /**
     * 删除菜单
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //判断能不能删除
            $count_menu = WechatMenu::where('pid',$param['id'])->count();
            if($count_menu >= '1'){
                $this->error('请先删除子菜单');
            }
            WechatMenu::destroy($param['id']);
            WechatMenu::update_menu($param['pid']);
            insert_user_log('删除了菜单');
            $this->success('删除成功');
        }
    }
    
}
